package com.huineta.business.modules.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huineta.business.common.context.UserContext;
import com.huineta.business.modules.sys.domain.SysMenu;
import com.huineta.business.modules.sys.mapper.SysMenuMapper;
import com.huineta.business.modules.sys.service.ISysMenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Resource
    private UserContext userContext;

    @Override
    public List<SysMenu> tree() {
        // List to Tree
        return toTree(sysMenuMapper.selectPermission(),"0");
    }

    @Override
    public List<SysMenu> treeByTenantId() {
        String tenantId = userContext.getTenantId();
        return toTree(sysMenuMapper.selectMenuByTenantId(tenantId),"0");
    }

    public List<SysMenu> toTree(List<SysMenu> sysMenus, String parent) {
        List<SysMenu> list = new ArrayList<>();
        for (SysMenu menu : sysMenus) {
            if (parent.equals(menu.getParent())) {
                menu.setChildren(toTree(sysMenus, menu.getId()));
                list.add(menu);
            }
        }
        return list;
    }
}
